#include "googletile.h"
#include <QUrl>

GoogleTile::GoogleTile(QObject *parent)
    : QObject(parent)
{
}

GoogleTile::GoogleTile(int x, int y, int z)
{
    mX = x;
    mY = y;
    mZ = z;
    mImage = NULL;
    mResolution = GetResolutionByLevel(z);
    mGeoExtent.minx = -MAX_RANGE + x * TILE_SIZE * mResolution;
    mGeoExtent.maxx = mGeoExtent.minx + mResolution*TILE_SIZE;
    mGeoExtent.maxy = MAX_RANGE - y*TILE_SIZE*mResolution;
    mGeoExtent.miny = mGeoExtent.maxy - mResolution*TILE_SIZE;

    QString url;
    url.sprintf("http://mt3.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&x=%d&y=%d&z=%d", x, y, z);
    httpGetter.startRequest(QUrl(url));
    connect(&httpGetter,SIGNAL(dataDownloaded()),
                     this, SLOT(ImageDownloaded()));
}

GoogleTile::~GoogleTile()
{
    delete mImage;
    mImage = NULL;
}

double GoogleTile::GetResolutionByLevel(int level)
{
    double resolution = MAX_RANGE / TILE_SIZE * 2;
    for (int i = 0; i < level; i++)
    {
        resolution /= 2;
    }
    return resolution;
}

void GoogleTile::ImageDownloaded()
{
    mImage = new QImage();
    mImage->loadFromData(httpGetter.getImgData());
    emit finished(this);
}


int GoogleTile::getMX() const
{
    return mX;
}

void GoogleTile::setMX(int value)
{
    mX = value;
}
int GoogleTile::getMY() const
{
    return mY;
}

void GoogleTile::setMY(int value)
{
    mY = value;
}
int GoogleTile::getMZ() const
{
    return mZ;
}

void GoogleTile::setMZ(int value)
{
    mZ = value;
}
QImage *GoogleTile::getMImage() const
{
    return mImage;
}

void GoogleTile::setMImage(QImage *value)
{
    mImage = value;
}
GeoExtent GoogleTile::getMGeoExtent() const
{
    return mGeoExtent;
}

void GoogleTile::setMGeoExtent(const GeoExtent &value)
{
    mGeoExtent = value;
}





